<?php

namespace Modules\Api\Controllers;

use Lib\Response;
use Lib\Consts;
use Models\Api\Manager;
use Models\Api\RoleRule;
use Models\Api\Rule;
use Models\Api\Role;
use Models\Api\User;
use Phalcon\Paginator\Adapter\QueryBuilder;

class AdminController extends ControllerBase {
    public function loginAction() {
//        var_dump($this->security->hash("jlz"));die();
//        $this->view->setTemplateBefore('login');

        if ($this->request->isPost()) {
//            $username = (string)trim($this->request->getPost('username'));
//            $password = (string)trim($this->request->getPost('password'));
            $username = $this->json("username");
            $password = $this->json("password");

            $mapper = new Manager();
            $model  = $mapper->findFirst('username="' . $username . '" AND status!=' . Consts::USER_DELETE);

            if (empty($username)) {
                return Response::errmsg('用户名不能为空', 10001);
            }

            if (empty($password)) {
                return Response::errmsg('密码不能为空', 10002);
            }

            if (!$model instanceof Manager) {
                return Response::errmsg('用户名或密码有误',10003);
            }

            if (!$this->security->checkHash($password, $model->getPassword())) {
                return Response::errmsg('用户名或密码有误', 10003);
            }

            //var_dump($this->session->get('auth'));//die();
            $this->session->set('auth', [
                'uid'        => $model->getId(),
                'username'   => $model->getUsername(),
                'login_time' => time(),
                'role_id'    => $model->getRoleId(),
            ]);
            return Response::msg('登录成功', '/');
        }
    }

    public function logoutAction() {
        $this->session->remove('auth');
        $this->session->remove('menu');
        $this->response->redirect('/' . Consts::ADMIN_NAME . '/admin/login');
        return false;
    }

    public function getinfoAction() {
        $auth = $this->session->get('auth');

        if (empty($auth)) {
            return Response::errmsg('请登录', 10004);
        }

        $username = $auth["username"];
        $roleId = $auth["role_id"];
        $mapper = new Manager();
        $model  = $mapper->findFirst('username="' . $username . '" AND status!=' . Consts::USER_DELETE);

        //===========================================
        $ruleAlias = 'Models\Api\Rule';
        $roleRuleAlias = 'Models\Api\RoleRule';
        $roleRuleMapper = new RoleRule();
        $builder = $roleRuleMapper->getModelsManager();
        $builder = $builder->createBuilder();
        $rows = $builder
//            ->columns(array('role_rule.role_id,','role_rule.rule_id'))
            ->from($ruleAlias)
            ->leftJoin($roleRuleAlias, "$ruleAlias.rule_id = $roleRuleAlias.rule_id and $roleRuleAlias.role_id=2")
            ->getQuery()
            ->execute();
        $menuData = [];
        foreach ($rows as $item) {
            if ($item->getRuleId() == 0) {
                $menuData[] = $item->toArray();
            }
        }

        foreach ($menuData as $key => $menuDatum) {
            foreach ($rows as $item) {
                if ($menuDatum["id"] == $item->getRuleId() ) {
                    $menuData[$key]["child"][] = $item->toArray();
                }
            }
        }
        //===========================================
        $ruleNames = [];
        foreach ($rows as $item) {
            if (!empty($item->getCondition())) {
                $ruleNames[] = $item->getCondition() . "," . $item->getMethod();
            }
        }

        //===========================================
        $roleMapper = new Role();
        $roleModel  = $roleMapper->findFirst("id=$roleId");

        if (empty($roleModel->toArray())) {
            return Response::errmsg('角色异常', 10005);
        }

        //===========================================
        $data = [
            "username" => $model->getUsername(),
            "avatar" => $model->getAvatar(),
            "super" => 1,
            "role" => [
                "id" => $roleId,
                "name" => $roleModel->getName(),
            ],
            "menus" => $menuData,
            "ruleNames" => $ruleNames,
        ];
        /*
        "id": 3,
		"username": "admin",
		"avatar": "http://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/public/62af03d1b2aeb.jpg",
		"super": 1,
		"role": {
            "id": 2,
			"name": "超级管理员"
		}
        */

        return Response::sucmsg($data);
    }

    /*
    public function listAction() {
        $page   = (int)$this->request->getQuery('page', null, 1);
        $limit  = 20;
        $where  = '';
        $mapper = new Admin();

        $builder = $mapper->getModelsManager();
        $builder = $builder->createBuilder();
        $builder->where($where);
        $builder->from('Models\Services\Admin');
        $builder->orderBy('id DESC');

        $paginator = new QueryBuilder([
            'builder' => $builder,
            'limit'   => $limit,
            'page'    => $page,
        ]);

        $pageData = $paginator->getPaginate();
        $data     = $pageData->items->toArray();
        $this->view->setVar('lists', $data);
        $this->view->setVar('pageData', $pageData);
    }

    public function addAction() {
        $username = (string)trim($this->request->getPost('username'));
        $password = (string)trim($this->request->getPost('password'));

        $model = new AdminModel();

        if($this->request->isPost()) {
            $cryptPassword = $this->security->hash($password);

            $model->setUsername($username);
            $model->setPassword($cryptPassword);
            $model->setStatus(Consts::USER_NORMAL);
            $model->setLast_login_ip(Tool::clientIp());
            $model->setAdd_time(time());

            $errMsg = $this->validate($model);

            if($errMsg !== false) {
                return Response::errmsg($errMsg);
            }

            try {
                $model->create();
                return Response::msg('添加成功');
            } catch(\Exception $exc) {
                return Response::errmsg($exc->getMessage());
            }
        }

        $this->view->setVar('model', $model);
        $this->view->setTemplateBefore('default');
        $this->view->render('user', 'edit');

        return false;
    }*/

    /*public function editAction() {
        $request = $this->request;
        $roleId  = (int)$request->getPost('role_id');
        $id      = (int)$request->getQuery("id");
        $data    = $model = [];

        if ($id > 0) {
            $model = Admin::findFirstById($id);

            if (!$model instanceof Admin) {
                return Response::errmsg('invalid id');
            }

            $data = $model->toArray();
        }

        if ($this->request->isPost()) {

            $username = $request->getPost("username");
            $password = $request->getPost("password");
            $mobile   = $request->getPost("mobile");
            $status   = (int)$this->request->getPost('status');

            if (empty($username)) {
                return Response::errmsg('用户名不能为空');
            }

            if ($roleId <= 0) {
                return Response::errmsg('角色不能为空');
            }

            if (empty($mobile)) {
                return Response::errmsg('手机号不能为空');
            }

            if (empty($password)) {
                return Response::errmsg('密码不能为空');
            }

            if (empty($model)) {
                $model    = new Admin();
                $password = $this->security->hash($password);
                $model->setAddTime(time());
                $model->setUsername($username);
                $model->setPassword($password);
                $model->setStatus($status);
                $model->setLastLoginIp(Tool::clientIp());
                $model->setRoleId($roleId);
                $model->setMobile($mobile);

                $uModel = Admin::findFirstByUsername($username);

                if ($uModel instanceof Admin) {
                    return Response::errmsg('用户名不能重复');
                }
            } else {
                $model->setStatus($status);
            }

            try {
                if ($model->save() === false) {
                    return Response::errmsg('编辑失败');
                }

                return Response::msg('编辑成功');
            } catch (\Exception $exc) {
                return Response::errmsg($exc->getMessage());
            }
        }

        $roleMapper = new RoleModel();
        $roleModel  = $roleMapper::find(['status=' . Consts::ROLE_NORMAL . " AND id!=1"]);
        //var_dump($roleModel->toArray());die();
        //var_dump($roleMapper->find('status=1')->toArray());die();
        //var_dump($model->toArray());die();

        $this->view->setVar('model', $data);
        $this->view->setVar('roleData', $roleModel->toArray());
    }

    public function editAction() {
        $request = $this->request;
        $roleId  = (int)$request->getPost('role_id');
        $data    = $model = [];

        if ($this->request->isPost()) {

            $username = $request->getPost("username");
            $password = $request->getPost("password");
            $mobile   = $request->getPost("mobile");
            $status   = (int)$this->request->getPost('status');

            if (empty($username)) {
                return Response::errmsg('用户名不能为空');
            }

            if ($roleId <= 0) {
                return Response::errmsg('角色不能为空');
            }

            if (empty($mobile)) {
                return Response::errmsg('手机号不能为空');
            }

            if (empty($password)) {
                return Response::errmsg('密码不能为空');
            }

            $model    = new Admin();
            $password = $this->security->hash($password);
            $model->setAddTime(time());
            $model->setUsername($username);
            $model->setPassword($password);
            $model->setStatus($status);
            $model->setLastLoginIp(Tool::clientIp());
            $model->setRoleId($roleId);
            $model->setMobile($mobile);

            $uModel = Admin::findFirstByUsername($username);

            if ($uModel instanceof Admin) {
                return Response::errmsg('用户名不能重复');
            }

            try {
                if ($model->save() === false) {
                    return Response::errmsg('编辑失败');
                }

                return Response::msg('编辑成功');
            } catch (\Exception $exc) {
                return Response::errmsg($exc->getMessage());
            }
        }

        $roleMapper = new RoleModel();
        $roleModel  = $roleMapper::find(['status=' . Consts::ROLE_NORMAL . " AND id!=1"]);

        $this->view->setVar('model', $data);
        $this->view->setVar('roleData', $roleModel->toArray());
    }

    public function delAction() {
        $id     = (int)$this->request->get('id');
        $mapper = new Admin();
        $model  = $mapper::findFirst('id=' . $id);

        if (!$model instanceof Admin) {
            return Response::errmsg('无此数据');
        }

        try {
            //$model->delete();
            $model->setUpdateTime(time());
            $model->setStatus(Consts::USER_DELETE);
            $model->save();
            return Response::msg('删除成功');
        } catch (\Exception $e) {
            return Response::errmsg($e->getMessage());
        }
    }

    /*private function validate(AdminModel $model) {
        if(empty($model->getUsername())) {
            return '账号名不能为空';
        }

        if(empty($model->getPassword())) {
            return '密码不能为空';
        }

        return false;
    }

    public function list2Action() {
        $page   = (int)$this->request->getQuery('page', null, 1);
        $limit  = 20;
        $where  = '';
        $mapper = new WxMember();

        $builder = $mapper->getModelsManager();
        $builder = $builder->createBuilder();
        $builder->where($where);
        $builder->from('Models\Services\WxMember');
        $builder->orderBy('id DESC');

        $paginator = new QueryBuilder([
            'builder' => $builder,
            'limit'   => $limit,
            'page'    => $page,
        ]);

        $pageData = $paginator->getPaginate();
        $data     = $pageData->items->toArray();

        foreach ($data as $key => $value) {
            $data[$key]["nickname"] = urldecode($value["nickname"]);
        }

        $this->view->setVar('lists', $data);
        $this->view->setVar('pageData', $pageData);
    }

    public function edit2Action() {
        $request = $this->request;
        $id      = (int)$request->get('id');
        $status  = (int)$request->get('status');

        $model = WxMember::findFirstById($id);

        if (!$model instanceof WxMember) {
            return Response::errmsg('invalid id');
        }

        if ($request->isPost()) {
            if ($status !== 1 && $status !== 2) {
                return Response::errmsg('invalid status');
            }

            $model->setUpdateTime(time());
            $model->setStatus($status);

            if ($status === 1) {
                $selectModel = WxMember::findFirstByStatus($status);

                if ($selectModel instanceof WxMember) {
                    $selectModel->setStatus($status);
                    $selectModel->setUpdateTime(time());
                }
            }

            try {
                $model->update();
                return Response::msg('编辑成功');
            } catch (\Exception $exc) {
                return Response::errmsg($exc->getMessage());
            }
        }

        $this->view->setVar('model', $model->toArray());
        $this->view->setVar('id', $id);
    }

    protected function sendMsg() {
        $data = \Lib\Queue::pop('sms');

        //array(2) { ["mobile"]=> string(11) "18046303205" ["content"]=> int(5244) }
        if (!isset($data["mobile"]) || !isset($data["content"])) {
            return false;
        }

        $mobile  = $data["mobile"];
        $content = $data["content"];
        $demo    = new \Lib\Aliyun\Send();

        $response = $demo->sendSms(
            "自然浮图", "SMS_98265008", $mobile, ["code" => $content], "song"
        );

        return false;
    }

    public function sendAction() {
        $beginTime = time();

        while (time() - $beginTime < 59) {
            if ($this->sendMsg() === false) {
                sleep(1);
            }
        }

        return false;
    }*/
}